<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue';
import { dayjs } from './utils';
import type { CountDownEmits, CountDownProps } from './types';

const INTERVAL_COUNT = 1000;

const props = withDefaults(defineProps<CountDownProps>(), {
  format: 'HH:mm:ss'
});
const emits = defineEmits<CountDownEmits>();

let duration = ref<number>(0);
let interval: number;
const start = () => {
  close();
  interval = setInterval(() => {
    durationFn();
  }, INTERVAL_COUNT);
};
const durationFn = () => {
  duration.value -= INTERVAL_COUNT;
  emits('change');

  if (duration.value <= 0) {
    duration.value = 0;
    emits('finish');
    close();
  }
};
const close = () => {
  if (interval) {
    clearInterval(interval);
  }
};

watch(
  () => props.time,
  val => {
    duration.value = val;
    start();
  },
  { immediate: true }
);

const showTime = computed(() =>
  dayjs.duration(duration.value).format(props.format)
);

onUnmounted(() => {
  close();
});
</script>

<template>
  <div>
    <slot>
      <p>{{ showTime }}</p>
    </slot>
  </div>
</template>
